# coding:utf-8
import time
from collections import namedtuple

from flask import current_app, g
from flask_httpauth import HTTPBasicAuth
import jwt

from app.libs.error_code import AuthFailed

auth = HTTPBasicAuth()
User = namedtuple('User', ['uid', 'ac_type', 'scope'])


@auth.verify_password
def verify_password(account, password):
    # token
    # HTTP 账号密码
    # header key:value
    # account  qiyue
    # 123456
    # key=Authorization
    # value =basic base64(qiyue:123456)
    user_info = verify_auth_token(account)
    if not user_info:
        return False
    else:
        # request
        g.user = user_info
        return True


def verify_auth_token(token):
    # key 是一个随机码，相当于给加密加盐，是加密数据更加不容易被破解
    key = current_app.config['SECRET_KEY']
    data = None
    try:
        # 需要解析的 jwt        密钥                使用和加密时相同的算法
        data = jwt.decode(token, key, algorithms=['HS256'])
    except Exception as e:
        # 如果 jwt 被篡改过; 或者算法不正确; 如果设置有效时间, 过了有效期; 或者密钥不相同; 都会抛出相应的异常
        raise AuthFailed(message='token is invalid', error_code=1002)
    if time.localtime(data['expiration']) < time.localtime():
        raise AuthFailed(message='Token 已过期', error_code=1002)
    # 解析出来的就是 payload 内的数据
    uid = data['uid']
    ac_type = data['type']
    scope = data['scope']
    print(data)
    return User(uid, ac_type, scope)
